package com.fwmagic.springcloud.controller;

import com.fwmagic.springcloud.entities.CommonResult;
import com.fwmagic.springcloud.entities.Payment;
import com.fwmagic.springcloud.lb.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/payment")
@Slf4j
public class PaymentController {

    @Value("${server.port}")
    private Integer serverPort;

    @Resource
    private DiscoveryClient discoveryClient;

    @Resource
    private PaymentService paymentService;

    @PostMapping("/create")
    public CommonResult create(@RequestBody Payment payment) {
        int result = paymentService.create(payment);
        log.info("*****插入操作返回结果:{}", result);
        if (result > 0) {
            return new CommonResult(200, "插入数据成功,服务端口：" + serverPort, result);
        } else {
            return new CommonResult(444, "插入数据失败,服务端口：" + serverPort, result);
        }
    }

    @GetMapping("/get/{id}")
    public CommonResult getPaymentById(@PathVariable("id") Long id) {
       /* try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }*/
        Payment payment = paymentService.getPaymentById(id);
        log.info("*****查询返回结果:{}", payment);
        if (payment != null) {
            return new CommonResult(200, "查询成功,服务端口：" + serverPort, payment);
        } else {
            return new CommonResult(444, "没有对应记录：" + id);
        }
    }

    @GetMapping("/discovery")
    public Object discovery() {
        List<String> services = discoveryClient.getServices();
        for (String service : services) {
            //***** lb:cloud-payment-service *****
            //***** lb:cloud-order-service *****
            log.info("***** lb:{} *****", service);
        }

        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        for (ServiceInstance instance : instances) {
            //CLOUD-PAYMENT-SERVICE	payment8001	192.168.1.6	8001	http://192.168.1.6:8001
            //CLOUD-PAYMENT-SERVICE	payment8002	192.168.1.6	8002	http://192.168.1.6:8002
            log.info(instance.getServiceId() + "\t" + instance.getInstanceId() + "\t" + instance.getHost() + "\t" + instance.getPort() + "\t" + instance.getUri());
        }
        return discoveryClient;
    }


    @GetMapping("/lb")
    public Object getPaymentLb() {
        return serverPort;
    }

    @GetMapping("/zipkin")
    public Object paymentZipkin() {
        return "payment zipkin!";
    }

}